package com.lagou.gateway.configuration;

import com.lagou.gateway.CORSItem;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.List;

@Configuration
@ConditionalOnProperty(value = "spring.cloud.gateway.cors.enabled",havingValue = "true")
@ConfigurationProperties("spring.cloud.gateway.cors")
public class CORSConfig {
    List<CORSItem> corsConfig;

    public void setCorsConfig(List<CORSItem> corsConfig) {
        this.corsConfig = corsConfig;
    }

    @Bean
    public CorsWebFilter corsFilter() {
        UrlBasedCorsConfigurationSource source
                = new UrlBasedCorsConfigurationSource(new PathPatternParser());

        corsConfig.forEach(c->{
            CorsConfiguration config = new CorsConfiguration();
            c.getAllowedMethods().forEach(s -> config.addAllowedMethod(s));
            c.getAllowedOrigins().forEach(s -> config.addAllowedOrigin(s));
            c.getAllowedHeaders().forEach(s -> config.addAllowedHeader(s));
            config.setAllowCredentials(true);
            source.registerCorsConfiguration(c.getPath(), config);
        });
        return new CorsWebFilter(source);
    }


}
